#
# Package.
#

package iSOCK::Model::Mail;

#
# Base.
#

use Moose;
use namespace::autoclean;

BEGIN { extends 'Catalyst::Model' }

#
# Dependencies.
#

use Date::Calc qw( Date_to_Text_Long );
use MIME::Lite;
use Try::Tiny;

#
# Subs.
#

sub done {
  my ( $self, $option ) = @_;
  
  my $with    = $option->{with};
  my $c       = $option->{c};
  my $session = $c->session;
  
  my $address;
  
  if ( $option->{user_ids} ) {
    $address = join ', ',
      sort
      map { $_->mail_address }
      grep { defined }
      map { $c->model ( 'App::User' )->find ( $_ ) }
      @{$option->{user_ids}}
    ;
  }
  elsif ( my $user_r = $c->model ( 'App' )->user_r ( $c ) ) {
    $address = $user_r->mail_address;
  }
  
  if ( $address ) {
    #
    # MIME.
    #
    
    my $mime = MIME::Lite->new (
      From    => $c->config->{self_mail},
      To      => $address,
      Subject => "[iSOCK] done with $with" . ( $option->{topic} ? " ($option->{topic})" : "" ),
      Type    => 'TEXT',
      Data    => ( $session->{session_started} && $session->{session_done} ?
        "Session start : " . _textish ( $session->{session_started} ) . "\n"
      . "Session end   : " . _textish ( $session->{session_done}    ) . "\n"
      . "Session ID    : " . $c->sessionid                            . "\n"
      : "" ),
    );

    #
    # Attachments.
    #

    if ( -f "$session->{session_path}/isock_${with}.log" ) {
      $mime->attach (
        Type        => 'text/plain',
        Path        => "$session->{session_path}/isock_${with}.log",
        Filename    => 'isock_product.log',
        Disposition => 'attachment'
      );
    }

    my $log_stem = {
      process_followup        => 'sock_followup_to_whatever',
      process_specification   => 'sock_specification_to_spirit',
      integrate_specification => 'sock_integrate_product',
      do_lint                 => 'sock_lint_datasheet',
    };

    for my $key ( sort grep { $session->{$_} } keys %$log_stem ) {
      my $file = "$log_stem->{$key}.log";
      
      if ( -f "$session->{session_path}/$file" ) {
        $mime->attach (
          Type        => 'text/plain',
          Path        => "$session->{session_path}/$file",
          Filename    => $file,
          Disposition => 'attachment'
        );
      }
    }
    
    if ( $option->{attachments} ) {
      for ( @{$option->{attachments}} ) {
        my ( $file, $type ) = ( @$_ );
        
        if ( -f "$session->{session_path}/$file" ) {
          my ( $name ) = ( $file =~ / ([^\/]+) $/x );
          
          $mime->attach (
            Type        => $type,
            Path        => "$session->{session_path}/$file",
            Filename    => $name,
            Disposition => 'attachment'
          );
        }
      }
    }

    #
    # Send.
    #

    try {
      $mime->send ({ smtp => $c->config->{smtp_host}, Debug => 0 });

      return $mime->last_send_successful;
    };
  }
  
  return;
}

sub send {
  my ( $self, $option ) = @_;
  
  my $config = $option->{c}->config;
  
  for ( $option->{mails} ? @{$option->{mails}} : $option->{mail} ) {
    $_->{From} ||= $config->{self_mail};
    $_->{To}   ||= $config->{root_mail};
    $_->{Type} ||= 'TEXT';
    
    unless ( $option->{dummy} ) {
      MIME::Lite->new ( %$_ )->send ( smtp => $config->{smtp_host}, Debug => $option->{debug} );
    }
  }
  
  return $option->{mails} ? $option->{mails} : $option->{mail};  
}

sub _textish {
  my ( $today_and_now ) = @_;
  
  Date_to_Text_Long ( $today_and_now->[0], $today_and_now->[1], $today_and_now->[2] ) . ' at ' . join ( ':', map { sprintf '%02d', $_ } $today_and_now->[3], $today_and_now->[4], $today_and_now->[5] );
}

#
# True.
#

1;
